package ricky.utils
{
	import flash.display.Stage;
	import flash.display.StageQuality;
	import flash.events.Event;
//	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import ricky.Interface.IAct;
	import ricky.Interface.IFrameManager;
	
	/**
	 * 帧管理器
	 */
	public class FrameManager implements IFrameManager
	{
		
		public function FrameManager()
		{
			if(!_instanced)
			{
				throw new Error("不能用new 实例化！请调用FrameManager.inst");
			}
			
			li=new Vector.<IAct>();
			animLi=new Vector.<IAct>();
		}
		
		public function get stage():Stage
		{
			return _stage;
		}

		public function set stage(value:Stage):void
		{
			_stage = value;
			_stage.removeEventListener(Event.ENTER_FRAME,update);
			_stage.addEventListener(Event.ENTER_FRAME,update);
		}

		public function add(ani:IAct):Boolean
		{
			var i:int=animLi.indexOf(ani);
			if(i==-1)
				animLi.push(ani);

			return true;
		}
		
		public function remove(ani:IAct):Boolean
		{
			var i:int=animLi.indexOf(ani);
			if(i>=0)
				animLi.splice(i,1);
			return true;
		}
		
		/**
		 * 推荐直接使用add(ani:IAct)方法
		 * 添加逻辑函数
		 * @param lis:Function function(dt):void dt为时间戳
		 */
		public function addLogic(lis:IAct):Boolean
		{
			var i:int=li.indexOf(lis);
			if(i==-1)
				li.push(lis);

			return true;
		}
		
		/**
		 * 推荐直接使用remove(ani:IAct)方法
		 * 移除函数监听
		 */
		public function removeLogic(lis:IAct):Boolean
		{
			var i:int=li.indexOf(lis);
			if(i>=0)
				li.splice(i,1);
			return true;
		}
		
		public function update(e:Event):void
		{
			timer = TimeServer.now();
			_fps++;
			
			if( timer - 1000 > msPrev )
			{
				msPrev = timer;
				fps1=_fps;
				_fps = 0;
			}
			dt=timer-ms;
			ms = timer;

			for each(var f:IAct in li)
			{
				f.action(timer);
			}
			
			var t:Number=timer/1000;
			
			for each(var i:IAct in animLi)
					i.action(t);
					
		}

		public function get fps():Number
		{
			return fps1;
		}
		
		//////////////////////
		//\属性
		//////////////////////
			
		private var timer:Number,dt:Number;
		
		private var _fps:int=0,fps1:int;
		
		private var msPrev:Number=TimeServer.now(),ms:Number;
		
		private var _stage:Stage;//用于改变品质的
		
		private var animLi:Vector.<IAct>;//动画调用列表
		
		private var li:Vector.<IAct>;//逻辑函数调用列表
		
		private  static var _inst:FrameManager;
		
		public static function get inst():FrameManager
		{
			if(_inst==null)
			{
				_instanced=true;
				_inst=new FrameManager();
				_instanced=false;
			}
			return _inst;
		}
		
		private static var _instanced:Boolean=false;

		
	}
}